import org.omg.CORBA.PUBLIC_MEMBER;

import java.awt.font.TextMeasurer;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;

public class TextHeap {
    int[] elem;
    int usedSize;
    public TextHeap() {

        elem = new int[10];
    }
    public void initHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }
    public void createHeap() {
          for(int parent = (usedSize-1-1)/2; parent >= 0; parent--) {
              shiftDown(parent,usedSize);
          }
    }
    //向下调整
    public void shiftDown(int parent,int len) {
          int child = parent * 2 + 1;
          //最起码有左孩子
          while (child < len) {
              if (child + 1 < len && elem[child] < elem[child+1]) {
                  child++;
              }
              if (elem[child] > elem[parent]) {
                  int tmp = elem[child];
                  elem[child] = elem[parent];
                  elem[parent] = tmp;
              } else {
                  break;
              }
          }
    }
    //向上调整
    public void shiftUp(int child) {
          int parent = (child - 1) / 2;
          while (child > 0) {
              if (elem[parent] < elem[child]) {
                  int tmp = elem[parent];
                  elem[parent] = elem[child];
                  elem[child] = tmp;
                  child = parent;
                  parent = (child - 1) / 2;
              }else {
                  break;
              }
          }
    }
    //向上调整建堆
    public void offer(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem,elem.length * 2);
        }
        elem[usedSize++] = val;
        shiftUp(usedSize-1);

    }
    public boolean isFull() {
        return usedSize == elem.length;
    }
    public void pop() {
        if (isEmpty()) {
            return ;
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
    }
    public boolean isEmpty() {

        return usedSize == 0;
    }
    public int peek() {
        return elem[0];
    }
    public int[] maxK(int[] arr,int k) {
        int[] ret = new int[k];
        if(arr == null || k == 0) {
            return ret;
        }
        Queue<Integer> minHeap = new PriorityQueue<>();
        for (int i = 0; i < k; i++) {
            minHeap.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            if (arr[i] > minHeap.peek()) {
                   minHeap.poll();
                minHeap.offer(arr[i]);
            }
        }
        for (int i = 0; i < k;i ++) {
            ret[i] = minHeap.poll();
        }
        return ret;
    }
}
